﻿using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using ComApp.Model;
using ComApp;

namespace AndroidApp
{
    [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class UploadView : BaseActivity
    {
        private Button selectFileButton;
        private Button cancelUploadButton;
        private ProgressBar progressBar;
        private TextView fileInfoTextView;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            //this.RequestWindowFeature(WindowFeatures.NoTitle); //不可行
            this.SetChildContentView(Resource.Layout.UploadView);
            AppUnity.Instance.LogService.Log("Open UploadView成功");

            selectFileButton = FindViewById<Button>(Resource.Id.selectFileButton);
            selectFileButton.Click += (s, e) =>
            {
                this.ShowFileChooser();
            };

            cancelUploadButton = FindViewById<Button>(Resource.Id.cancelUploadButton);
            cancelUploadButton.Click += (s, e) =>
            {
                this.CancelUpload();
            };

            progressBar = FindViewById<ProgressBar>(Resource.Id.uploadProgress);
            fileInfoTextView = this.FindViewById<TextView>(Resource.Id.fileInfoTextView);
            this.SetUploadView();
        }

        private void CancelUpload()
        {
            HttpService.Instance.CancelUpload();
            this.SetUploadView();
            Toast.MakeText(this, "上传取消.", ToastLength.Short).Show();
            AppUnity.Instance.LogService.Log("上传取消");
        }

        private void ShowFileChooser()
        {
            Intent intent = new Intent(Intent.ActionGetContent);
            intent.SetType("*/*");
            intent.AddCategory(Intent.CategoryOpenable);

            try
            {
                this.StartActivityForResult(Intent.CreateChooser(intent, "选择文件"), FILE_SELECT_CODE);
            }
            catch
            {
                Toast.MakeText(this, "请安装文件管理器.", ToastLength.Short).Show();
            }
        }

        public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
        {
            if (keyCode == Keycode.Back)
            {
                this.CloseViewAndExitApp();
                return false;
            }

            return base.OnKeyDown(keyCode, e);
        }


        /// <summary>
        /// 从任务栏移走，会CloseBeforeExit，但不会提示
        /// 回退到桌面会提示退出，相当于应用退出 
        /// 隐藏到后台重新激活（从任务栏或桌面），会刷新，但没有退出过
        /// 还需要测试打开另一个Activity的情况
        /// </summary>
        protected override bool CloseBeforeExit()
        {

            return true;
        }

        bool isFirst = true;
        protected override void OnResume()
        {
            base.OnResume();
            if (isFirst)
            {
                isFirst = false;
                AppUnity.Instance.LogService.Log("UploadView.OnResume First...");
            }
            else
            {
                AppUnity.Instance.LogService.Log("UploadView.OnResume More...");
            }
        }

        public static int NONE = 0;
        public static int FILE_SELECT_CODE = 1;
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (resultCode != Result.Ok)
                return;

            if (requestCode == NONE)
                return;

            if (requestCode == FILE_SELECT_CODE)
            {
                if (data == null)
                    return;

                Android.Net.Uri uri = data.Data;
                var filePath = this.GetPath(this, uri);
                if (string.IsNullOrEmpty(filePath))
                    return;

                if (!System.IO.File.Exists(filePath))
                    return;

                this.UploadFile(filePath);
            }

            base.OnActivityResult(requestCode, resultCode, data);
        }


        private void UploadFile_2(string filePath)
        {
            var fileName = System.IO.Path.GetFileName(filePath);
            var uploadUrl = string.Format("{0}?qqfilename={1}", AppUnity.Instance.ServerDeploy.WebUploadFileUrl, fileName);

            HttpClient client = new HttpClient();
            client.Url = uploadUrl;
            client.Verb = HttpVerb.POST;
            client.AttachFile(filePath, "file");
            Action<string> complete = (s) => AppUnity.Instance.RunOnUiThread(() => this.selectFileButton.Text = "选择文件");
            int i = 0;
            int m = 0;
            string sText = string.Empty;
            Action sendMsg = () =>
            {
                m++;
                if (m > i * 2)
                {
                    AppUnity.Instance.RunOnUiThread(() =>
                    {
                        sText += '.';
                        if (sText == "....")
                            sText = string.Empty;
                        this.selectFileButton.Text = string.Format("上传中{0}", sText);
                    });
                    i++;
                }
            };
            client.GetResponseAsync(complete, sendMsg);
        }



        private void UploadFile(string filePath)
        {
            var fileName = System.IO.Path.GetFileName(filePath);
            var uploadUrl = string.Format("{0}?qqfilename={1}", AppUnity.Instance.ServerDeploy.WebUploadFileUrl, fileName);
            Action<string> uploaded = (s) =>
                {
                    this.SetUploadView();
                    var result = SimpleJson.SimpleJson.DeserializeObject<UploadResultJson>(s);
                    if (result.success)
                    {
                        AppUnity.Instance.LogService.Log("上传完成.");
                        this.CreateTempFile(result.fileItemID);
                    }
                    else
                    {
                        AppUnity.Instance.LogService.Log("上传返回失败.");
                    }
                };
            try
            {
                this.SetUploadingView(filePath);
                HttpService.Instance.UploadFile(filePath, uploadUrl, null, uploaded, sendRunningMsg: null);
            }
            catch
            {
                AppUnity.Instance.LogService.Log("UPloadView.UploadFile()捕获异常.");
                this.SetUploadView();
                Toast.MakeText(this, "上传失败.", ToastLength.Short).Show();
            }
        }

        private void CreateTempFile(Guid fileItemID)
        {
            //打开上传结果页
            using (var client = new WcfTempFileServiceRef.WcfTempFileService())
            {
                AppUnity.Instance.LogService.Log(string.Format("调用{0}.CreateTempFile()", AppUnity.Instance.ServerDeploy.WcfTempFileUrl));
                client.Url = AppUnity.Instance.ServerDeploy.WcfTempFileUrl;
                client.CreateTempFileCompleted += (s, e) =>
                {
                    AppUnity.Instance.RunOnUiThread(() =>
                    {
                        var tempCode = e.Result;
                        Intent uploadedView = new Intent(this, typeof(UploadedView));
                        uploadedView.PutExtra("TempCode", tempCode);
                        AppUnity.Instance.LogService.Log("试图StartActivity(UploadedView)...");
                        this.StartActivity(uploadedView);
                    });
                };
                client.CreateTempFileAsync(fileItemID.ToString(), HttpService.Instance.GetLocalIpAddress(), ThisApp.Instance.AppDeploy.CurrentUser.ID.ToString(), "AndroidApp");
                Toast.MakeText(this, "正在生成下载链接....", ToastLength.Short).Show();
            }
        }

        private string GetFileSize(long fileLength)
        {
            var unit = "B";
            var fileSize = (decimal)fileLength;
            unit = "K";
            fileSize = ((decimal)fileSize / (decimal)1024);
            if (fileSize >= 1024)
            {
                unit = "M";
                fileSize = ((decimal)fileSize / (decimal)1024);
            }
            if (fileSize >= 1024)
            {
                unit = "G";
                fileSize = ((decimal)fileSize / (decimal)1024);
            }

            return string.Format("{0}{1}", fileSize.ToString("#,##0.#"), unit);
        }

        private void SetUploadView()
        {
            this.selectFileButton.Visibility = ViewStates.Visible;
            this.cancelUploadButton.Visibility = ViewStates.Gone;
            progressBar.Visibility = ViewStates.Gone;
            fileInfoTextView.Visibility = ViewStates.Gone;
        }

        private void SetUploadingView(string filePath)
        {
            this.selectFileButton.Visibility = ViewStates.Gone;
            this.cancelUploadButton.Visibility = ViewStates.Visible;
            this.progressBar.Visibility = ViewStates.Visible;
            fileInfoTextView.Visibility = ViewStates.Visible;
            var fileInfo = new System.IO.FileInfo(filePath);
            var fileText = System.IO.Path.GetFileNameWithoutExtension(filePath);
            var fileExt = System.IO.Path.GetExtension(filePath);
            fileInfoTextView.Text = string.Format("正在上传{0}{1}({2})", fileText.TrimOrDot(10), fileExt, this.GetFileSize(fileInfo.Length));
        }

        public string GetPath(Context context, Android.Net.Uri uri)
        {
            if (uri.Scheme.TrimOrEmpty().ToLower() == "content")
            {
                String[] projection = { "_data" };
                try
                {
                    var cursor = context.ContentResolver.Query(uri, projection, null, null, null);
                    int column_index = cursor.GetColumnIndexOrThrow("_data");
                    if (cursor.MoveToFirst())
                    {
                        return cursor.GetString(column_index);
                    }
                }
                catch
                {
                    // Eat it
                }
            }
            else if (uri.Scheme.TrimOrEmpty().ToLower() == "file")
            {
                return uri.Path;
            }

            return string.Empty;
        }
    }
}

